const ScrollTopRefKey = 'pageScrollTop'
const ScrollTopSetterKey = 'setPageScrollTop'

/**
 * 在页面上使用该方法 为组件注入页面高度
 */
export function useScrollProvider(): {
  scrollTopRef: Ref<number>
  setScrollTop: (scrollTop: number) => void
} {
  const scrollTopRef = ref(0)
  provide<Ref<number>>(ScrollTopRefKey, scrollTopRef)
  provide<(scrollTop: number) => void>(ScrollTopSetterKey, setScrollTop)
  function setScrollTop(scrollTop: number) {
    scrollTopRef.value = scrollTop
  }
  return {
    scrollTopRef,
    setScrollTop,
  }
}

/**
 * 在组件内使用该方法 获取从页面注入的页面高度
 */
export function useScrollInjection() {
  const scrollTopRef = inject<Ref<number>>(ScrollTopRefKey)
  const setScrollTop = inject<(scrollTop: number) => void>(ScrollTopSetterKey)
  if (!scrollTopRef) {
    throw new Error('[Error]: 请确认在页面上正确调用 "useScrollProvider", 否则组件内无法获取 scrollTop.')
  }
  return {
    scrollTopRef,
    setScrollTop,
  }
}
